package com.springboot.hikersystemapp.controller;

import com.springboot.hikersystemapp.domain.Team;
import com.springboot.hikersystemapp.domain.User;
import com.springboot.hikersystemapp.domain.TeamMember;
import com.springboot.hikersystemapp.repository.TeamMemberRepository;
import com.springboot.hikersystemapp.repository.TeamRepository;
import com.springboot.hikersystemapp.repository.UserRepository;
import com.springboot.hikersystemapp.dto.ChangePasswordRequest;
import com.springboot.hikersystemapp.dto.ChangeUsernameRequest;
import com.springboot.hikersystemapp.service.ServiceInterface;
import com.springboot.hikersystemapp.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class Controller {
    @Resource
    private ServiceInterface Service;
    @Autowired
    private TeamRepository teamRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private TeamMemberRepository teamMemberRepository;
    @Autowired
    private com.springboot.hikersystemapp.service.serviceImpl.servicempl servicempl;

    @PostMapping("/register")
    public Result<User> registController(@RequestBody User newUser){
        User user = Service.registService(newUser);
        if(user!=null)
        {
            if(user.getUsername().length()<4 || user.getUsername().length()>50)
            {
                return Result.error("456","用户名需4~50字符！");
            }
            if(user.getPassword().length()<6){
                return Result.error("456","密码至少6位！");
            }
            userRepository.save(user);
            servicempl.generateTeamMembers();
            return Result.success(user,"注册成功！");
        }
        else {
            return Result.error("456","用户已存在！");
        }
    }

    @PostMapping("/login")
    public Result<User> loginController(@RequestBody User userp){
        User user = Service.loginService(userp);
        if(user!=null)
        {
            return Result.success(user,"登录成功！");
        }
        else
        {
            return Result.error("123","账号或密码错误！");
        }
    }

    @PostMapping("/changePassword")
    public Result<String> changePasswordController(@RequestBody ChangePasswordRequest request) {
        boolean success = Service.changePassword(request.getUserId(), request.getOldPassword(), request.getNewPassword());
        if (success) {
            return Result.success("密码修改成功！");
        } else {
            return Result.error("789", "密码修改失败！");
        }
    }

    @PostMapping("/changeUsername")
    public Result<String> changeUsernameController(@RequestBody ChangeUsernameRequest request) {
        boolean success = Service.changeUsername(request.getUserId(), request.getNewUsername());
        if (success) {
            return Result.success("用户名修改成功！");
        } else {
            return Result.error("456", "用户名修改失败！");
        }
    }

    @GetMapping("/getUserList")
    public Result<List<User>> getUserListController() {
        List<User> userList = Service.getUserList();
        if (userList != null) {
            return Result.success(userList, "获取成功！");
        }else {
            return Result.error("202", "获取失败！");
        }
    }

    @PostMapping("/createTeam")
    public Result<Team> createTeamController(@RequestBody Map<String, Object> payload) {
        ObjectMapper mapper = new ObjectMapper();
        User user_parmer = mapper.convertValue(payload.get("user"), User.class);
        Team team = mapper.convertValue(payload.get("team"), Team.class);
        User user =userRepository.findById(user_parmer.getId()).orElse(null);
        List<Integer> idlist = mapper.convertValue(payload.get("idlist"), List.class);

        if (user == null || team == null) {
            return Result.error("789", "用户信息或队伍信息不能为空！");
        }
        Team createdTeam = Service.createTeam(user, team);

        if (createdTeam != null) {
            servicempl.generateTeamMembers();
            TeamMember  teamMember = teamMemberRepository.findByTeamIdAndUserId(team.getId(), user.getId());
            teamMember.setStatus("approval");
            team.setMax_members(team.getMax_members()-1);
            teamRepository.save(team);
            teamMemberRepository.save(teamMember);//管理

            for(Integer id:idlist)
            {
                TeamMember teamMember1 = teamMemberRepository.findByTeamIdAndUserId(team.getId(),id.longValue());
                teamMember1.setStatus("approval");
                teamMemberRepository.save(teamMember1);
            }
            team.setMax_members(team.getMax_members()-idlist.toArray().length);
            if(team.getMax_members()==0){
                team.setStatus("full");
            }
            teamRepository.save(team);

            return Result.success(createdTeam, "队伍创建成功！");
        } else {
            return Result.error("101", "队伍创建失败！");
        }
    }

    @PostMapping("/joinableTeamList")
    public Result<List<Team>> getJoinableTeamsController(@RequestBody Map<String, Object> payload) {
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.convertValue(payload.get("user"), User.class);
        User user_database = userRepository.findById(user.getId()).orElse(null);
        List<Team> joinableTeams = Service.getJoinableTeams(user_database);
        if (joinableTeams != null) {
            return Result.success(joinableTeams, "获取成功！");
        }else {
            return Result.error("202", "可加入队伍获取失败！");
        }
    }

    @PostMapping("/setTeamMember")
    public Result<Void> setTeamMemberController(@RequestBody Map<String, Object> payload) {
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.convertValue(payload.get("user"), User.class);
        Team team = mapper.convertValue(payload.get("team"), Team.class);
        User user_database = userRepository.findById(user.getId()).orElse(null);
        Team team_database = teamRepository.findById(team.getId()).orElse(null);

        if (user_database == null || team_database == null) {
            return Result.error("303", "用户信息或队伍信息不能为空！");
        }else{
            Service.setTeamMember(user_database, team_database);

            return Result.success(null, "成功申请加入队伍！");
        }

    }

    @PostMapping("/applicationList")
    public Result<List<TeamMember>> getApplicationListController(@RequestBody User newuser) {
        User user =userRepository.findById(newuser.getId()).orElse(null);
        List <TeamMember> applicationList = Service.getApplicationList(user);
        if (applicationList != null) {
            return Result.success(applicationList, "获取成功！");
        } else {
            return Result.error("404", "获取申请列表失败！");
        }
    }

    @PostMapping("/approveTeamMember")
    public Result<TeamMember> approveTeamMemberController(@RequestBody Map<String, Object> payload) {
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.convertValue(payload.get("user"), User.class);
        TeamMember teamMember = mapper.convertValue(payload.get("teamMember"), TeamMember.class);
        User user_database = userRepository.findById(user.getId()).orElse(null);
        TeamMember teamMember_database = teamMemberRepository.findById(teamMember.getId()).orElse(null);
        Team team=teamMemberRepository.findById(teamMember_database.getId()).orElse(null).getTeam();
        if(team.getStatus().equals("full"))
        {
            return Result.error("707","队伍已满，审核功能关闭");
        }
        if (user_database == null || teamMember_database == null) {
            return Result.error("505", "用户信息或队伍成员信息不能为空！");
        }
        TeamMember approvedTeamMember = Service.approveTeamMember(user_database, teamMember_database);
        if (approvedTeamMember != null) {
            return Result.success(approvedTeamMember, "成员审核通过！");
        } else {
            return Result.error("606", "成员审核失败！");
        }
    }

}
